import Request from '@/js_sdk/luch-request/luch-request/index.js'

export const http = new Request();

// 添加一个标记，避免重复跳转登录页
let isLoginNavigating = false

http.setConfig((config) => {
	config.baseURL = 'https://api.liangxibao.com/' /* 根域名 */
	config.custom = {
		loading: true // 默认有loading
	}
	return config
})

http.interceptors.request.use((config) => {
	/* 请求之前拦截器。可以使用async await 做异步操作 */
	// uni.setStorageSync('token', 'UsereyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI0MjA4MjIxOTkyMTAwNTY4NTYiLCJ1c2UiOnRydWUsImNyZWF0ZWQiOjE3NTM5ODE2NTk0NjQsImV4cCI6MTc1NDU4NjQ1OX0.2SmIbB55V1lKk308fj1AIXNBc-KNaKYAbvxpEwrd_Rr5cDpLd_n1CfmXZQ5BM1bvRMyJe1jYANWG6EqgJvInLg')
	const token = uni.getStorageSync('token')
	// const token = "UsereyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI0MjA4MjIxOTkyMTAwNTY4NTYiLCJ1c2UiOnRydWUsImNyZWF0ZWQiOjE3NTM5ODE2NTk0NjQsImV4cCI6MTc1NDU4NjQ1OX0.2SmIbB55V1lKk308fj1AIXNBc-KNaKYAbvxpEwrd_Rr5cDpLd_n1CfmXZQ5BM1bvRMyJe1jYANWG6EqgJvInLg"

	if (token) {
		config.header = {
			...config.header,
			authorization: token
		}
	}
	return config
}, (config) => {
	return Promise.reject(config)
})


http.interceptors.response.use(async (response) => {
	/* 请求之后拦截器。可以使用async await 做异步操作  */
	switch (response.data.code) {
		case 200:
			return response.data
			break
		case 500:
			uni.showToast({
				icon: 'none',
				title: response.data.message
			})
			return Promise.reject(response)
			break
		case 401:
			uni.clearStorageSync()
			// 避免重复处理 401
			console.log(isLoginNavigating);
			if (isLoginNavigating) {
				return Promise.reject(response)
			}
			isLoginNavigating = true
			
			// 获取当前页面路径
			const pages = getCurrentPages()
			const currentPage = pages[pages.length - 1]
			const currentPath = `/${currentPage.route}`
			
			// 如果当前已经在登录页，不再跳转
			if (currentPath.includes('/login')) {
				isLoginNavigating = false
				return Promise.reject(response)
			}
			console.log('请求401');
			uni.showModal({
				title: '请登录',
				content: '请先登录，否则无法继续操作',
				confirmText: '去登录',
				confirmColor: '#007AFF',
				cancelText: '取消',
				cancelColor: '#666',
				success: (e) => {
					if (e.confirm) {
						uni.setStorageSync('redirect', currentPath)
					uni.navigateTo({
						url: '/pages/login/login',
						complete: () => {
							isLoginNavigating = false
							}
						})
					}else{
						uni.switchTab({
							url: '/pages/index/index',
							success: () => {
								isLoginNavigating = false
							}
						})
					}
				}
			})

			// uni.showToast({
			// 	title: '请登录',
			// 	duration: 1500,
			// 	icon: 'none',
			// 	success: () => {
			// 		setTimeout(() => {
			// 			// 保存当前页面路径，登录后可以返回
			// 			uni.setStorageSync('redirect', currentPath)
						
			// 			uni.navigateTo({
			// 				url: '/pages/login/login',
			// 				complete: () => {
			// 					isLoginNavigating = false
			// 				}
			// 			})
			// 		}, 1500)
			// 	}
			// })
			return Promise.reject(response)
			break
		default:
			return Promise.reject(response)
	}
}, (error) => {
	console.error('请求错误:', error)
	if(error.data.code == 401){
		uni.clearStorageSync()
		uni.showToast({
			title: '请登录',
			icon: 'none'
		})
	}
	
	// 网络错误等情况的处理
	uni.showToast({
		title: '网络请求失败',
		icon: 'none'
	})
	
	return Promise.reject(error)
})